/**
 * API 工具配置
 * 统一管理与Django后端的API交互
 */

// 获取API基础URL
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '/api'
const BACKEND_BASE_URL = import.meta.env.VITE_BACKEND_BASE_URL || 'http://127.0.0.1:8000'

/**
 * 创建完整的API URL
 * @param {string} endpoint - API端点
 * @returns {string} 完整的API URL
 */
export const createApiUrl = (endpoint) => {
  // 确保endpoint以/开头
  const cleanEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`
  return `${API_BASE_URL}${cleanEndpoint}`
}

/**
 * 创建完整的后端URL（用于非API请求，如静态文件）
 * @param {string} path - 路径
 * @returns {string} 完整的后端URL
 */
export const createBackendUrl = (path) => {
  const cleanPath = path.startsWith('/') ? path : `/${path}`
  return `${BACKEND_BASE_URL}${cleanPath}`
}

/**
 * 通用的API请求配置
 */
export const apiConfig = {
  baseURL: API_BASE_URL,
  timeout: 10000, // 10秒超时
  headers: {
    'Content-Type': 'application/json',
  },
}

/**
 * 获取CSRF token
 * @returns {string|null} CSRF token
 */
export const getCSRFToken = () => {
  // 从cookie中获取CSRF token
  const cookies = document.cookie.split(';')
  for (let cookie of cookies) {
    const [name, value] = cookie.trim().split('=')
    if (name === 'csrftoken') {
      return decodeURIComponent(value)
    }
  }
  return null
}

/**
 * 通用的fetch请求封装
 * @param {string} endpoint - API端点
 * @param {object} options - 请求选项
 * @returns {Promise} 请求Promise
 */
export const apiRequest = async (endpoint, options = {}) => {
  const url = createApiUrl(endpoint)
  console.log('发送API请求:', { url, options })
  
  // 获取存储的access token
  const token = localStorage.getItem('access_token')
  
  // 获取CSRF token
  const csrfToken = getCSRFToken()
  
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
      ...(token && { 'Authorization': `Bearer ${token}` }),
      ...(csrfToken && { 'X-CSRFToken': csrfToken }),
      ...options.headers,
    },
    credentials: 'include', // 包含cookies
  }
  
  const requestOptions = {
    ...defaultOptions,
    ...options,
  }
  
  try {
    const response = await fetch(url, requestOptions)
    console.log('收到API响应:', { url, status: response.status, statusText: response.statusText })
    
    // 如果是302重定向到登录页面，说明需要登录
    if (response.status === 302 && response.headers.get('Location')?.includes('/accounts/login/')) {
      console.warn('用户未登录，需要重新登录')
      if (window.location.pathname !== '/login') {
        window.location.href = '/login'
      }
      throw new Error('用户未登录，请先登录')
    }
    
    if (!response.ok) {
      // 克隆响应以避免流已被读取的问题
      const clonedResponse = response.clone()
      const errorData = await clonedResponse.json().catch(() => ({ error: `HTTP error! status: ${response.status}` }))
      console.error('API请求失败:', { url, status: response.status, error: errorData })
      throw new Error(errorData.error || `HTTP error! status: ${response.status}`)
    }
    
    // 尝试解析响应数据
    // 克隆响应以避免流已被读取的问题
    const clonedResponse = response.clone()
    
    // 检查是否是blob响应（如图片代理请求）
    if (options.responseType === 'blob') {
      const blob = await response.blob()
      console.log('API响应数据（blob）:', { url, blob })
      return { data: blob }
    }
    
    try {
      const data = await clonedResponse.json()
      console.log('API响应数据:', { url, data })
      return data
    } catch (e) {
      const text = await clonedResponse.text()
      console.log('API响应文本:', { url, text })
      return text
    }
  } catch (error) {
    console.error('API请求失败:', error)
    throw error
  }
}

/**
 * 常用的API请求方法
 */
export const api = {
  // GET请求
  get: (endpoint, options = {}) => {
    // 处理GET请求的参数
    let url = endpoint;
    if (options.params) {
      const params = new URLSearchParams(options.params);
      url += (url.includes('?') ? '&' : '?') + params.toString();
      // 删除params属性，避免传递给fetch
      const { params: _, ...restOptions } = options;
      return apiRequest(url, { method: 'GET', ...restOptions });
    }
    return apiRequest(url, { method: 'GET', ...options });
  },
  
  // POST请求
  post: (endpoint, data, options = {}) => apiRequest(endpoint, {
    method: 'POST',
    body: JSON.stringify(data),
    ...options,
  }),
  
  // PUT请求
  put: (endpoint, data, options = {}) => apiRequest(endpoint, {
    method: 'PUT',
    body: JSON.stringify(data),
    ...options,
  }),
  
  // DELETE请求
  delete: (endpoint, options = {}) => apiRequest(endpoint, { method: 'DELETE', ...options }),
  
  // PATCH请求
  patch: (endpoint, data, options = {}) => apiRequest(endpoint, {
    method: 'PATCH',
    body: JSON.stringify(data),
    ...options,
  }),
}

export default api